package com.qf.controller;

import com.qf.entity.Goods;
import com.qf.service.GoodsService;
import com.qf.service.impl.GoodsServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.UUID;

/**
 * @author 10202
 * @version V1.0
 * @Project xiaomi
 * @Package ${PACKAGE_NAME}
 * @Date 2023/4/17 21:55
 */
@WebServlet(name = "AdminGoodsServlet" ,urlPatterns = "/addGoods")
@MultipartConfig
public class AdminGoodsServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String name = request.getParameter("name");
        String typeId = request.getParameter("typeid");
        String pubdate = request.getParameter("pubdate");
        String price = request.getParameter("price");
        String star = request.getParameter("star");
        String intro = request.getParameter("intro");
        Part picture = request.getPart("picture");

        String fileName = picture.getSubmittedFileName();
        if(fileName!=null&&!fileName.equals("")){
            String firstname = UUID.randomUUID().toString().replace("-","").substring(16);
            String ext = fileName.substring(fileName.lastIndexOf(".")+1);
            fileName=firstname+"."+ext;
        }
        String basePath = this.getServletContext().getRealPath("WEB-INF" + File.separator + "images");
        File file=new File(basePath);
        if(!file.exists()){
            file.mkdirs();
        }
        if(picture!=null){
            picture.write(basePath+File.separator+fileName);
        }
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        try {
            Goods goods=new Goods(null,name,sdf.parse(pubdate),fileName,new BigDecimal(price),Integer.parseInt(star),intro,Integer.parseInt(typeId));
            GoodsService goodsService=new GoodsServiceImpl();
            goodsService.addGoods(goods);
        } catch (ParseException e) {
            e.printStackTrace();
        }

    }





    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
